<template>
  <ContentWrap>
    <back :backOption="backOption" />
    <div class="mt-16px flex justify-end">
      <el-icon class="cursor-pointer" @click="isList = true"><List /></el-icon>
      <el-icon class="ml-12px cursor-pointer" @click="isList = false"><Menu /></el-icon>
    </div>
    <div v-if="isList">
      <el-card shadow="never" class="mt-16px">
        <template #header>
          <div class="flex">
            <span>{{ infoOptions.data.name || '--' }}</span>
            <el-button style="margin-left: auto" @click="openEditFormVisible">编辑</el-button>
          </div>
        </template>
        <el-descriptions :column="infoOptions.column">
          <div v-for="(item, index) in infoOptions.columns" :key="index">
            <el-descriptions-item :label="item.label">
              <div
                v-if="item.key == 'ip'"
                class="inline-flex"
                style="justify-content: space-between; width: 160px; align-items: center"
              >
                <span v-if="isShowIp" class="mr-10px">
                  {{ infoOptions.data.ip }}:{{ infoOptions.data.port }}
                </span>
                <span v-else class="mr-10px">**********</span>
                <el-Icon v-if="isShowIp"><Hide @click="isShowIp = false" /></el-Icon>
                <el-Icon v-else>
                  <View @click="isShowIp = true" />
                </el-Icon>
              </div>
              <span v-else-if="item.key == 'source'">
                {{
                  sourceMap.has(infoOptions.data.source)
                    ? sourceMap.get(infoOptions.data.source)
                    : '--'
                }}
              </span>
              <span v-else> {{ infoOptions.data[item.key] || '--' }}</span>
            </el-descriptions-item>
          </div>
        </el-descriptions>
      </el-card>
      <DatabaseInfo
        @renew="renew"
        :tree-data="treeData"
        class="mt-10px"
        :isList="isList"
        ref="dbInfoRef"
        :canAdd="route.query.canAdd"
        :sourceType="infoOptions.data.source"
      />
    </div>
    <div v-else>
      <el-tabs v-model="activeTab" class="demo-tabs">
        <el-tab-pane label="字段分类分级" name="field">
          <el-card shadow="never" class="mt-16px">
            <template #header>
              <span>{{ infoOptions.data.name || '--' }}</span>
            </template>
            <el-descriptions :column="infoOptions.column">
              <div v-for="(item, index) in infoOptions.columns" :key="index">
                <el-descriptions-item :label="item.label" v-if="item.isShow">
                  <div
                    v-if="item.key == 'ip'"
                    class="inline-flex"
                    style="justify-content: space-between; width: 160px; align-items: center"
                  >
                    <span v-if="isShowIp" class="mr-10px">
                      {{ infoOptions.data.ip }}:{{ infoOptions.data.port }}
                    </span>
                    <span v-else class="mr-10px">**********</span>
                    <el-Icon v-if="isShowIp"><Hide @click="isShowIp = false" /></el-Icon>
                    <el-Icon v-else>
                      <View @click="isShowIp = true" />
                    </el-Icon>
                  </div>
                  <span v-else-if="item.key == 'source'">
                    {{
                      sourceMap.has(infoOptions.data.source)
                        ? sourceMap.get(infoOptions.data.source)
                        : '--'
                    }}
                  </span>
                  <span v-else> {{ infoOptions.data[item.key] || '--' }}</span>
                </el-descriptions-item>
              </div>
            </el-descriptions>
            <el-descriptions :column="filedOptions.column" class="mt-16px">
              <div v-for="(item, index) in filedOptions.columns" :key="index">
                <el-descriptions-item
                  label-class-name="font-size-16px"
                  class-name="font-size-16px"
                  :label="item.label"
                  >{{ filedOptions.data[item.key] || '0' }}</el-descriptions-item
                >
              </div>
            </el-descriptions>
          </el-card>
          <DatabaseInfo
            ref="dbInfoRef"
            v-if="activeTab === 'field'"
            class="mt-10px"
            :isList="isList"
            tableShow="field"
            :canAdd="route?.query?.canAdd || false"
            @table-search="countSearch"
          />
        </el-tab-pane>
        <el-tab-pane label="表分类分级" name="table">
          <el-card shadow="never" class="mt-16px">
            <template #header>
              <span>{{ infoOptions.data.name || '--' }}</span>
            </template>
            <el-descriptions :column="infoOptions.column">
              <div v-for="(item, index) in infoOptions.columns" :key="index">
                <el-descriptions-item :label="item.label" v-if="item.isShow">
                  <div
                    v-if="item.key == 'ip'"
                    class="inline-flex"
                    style="justify-content: space-between; width: 160px; align-items: center"
                  >
                    <span v-if="isShowIp" class="mr-10px">
                      {{ infoOptions.data.ip }}:{{ infoOptions.data.port }}
                    </span>
                    <span v-else class="mr-10px">**********</span>
                    <el-Icon v-if="isShowIp"><Hide @click="isShowIp = false" /></el-Icon>
                    <el-Icon v-else>
                      <View @click="isShowIp = true" />
                    </el-Icon>
                  </div>
                  <span v-else-if="item.key == 'source'">
                    {{
                      sourceMap.has(infoOptions.data.source)
                        ? sourceMap.get(infoOptions.data.source)
                        : '--'
                    }}
                  </span>
                  <span v-else> {{ infoOptions.data[item.key] || '--' }}</span>
                </el-descriptions-item>
              </div>
            </el-descriptions>
            <el-descriptions :column="filedOptions.column" class="mt-16px">
              <div v-for="(item, index) in filedOptions.columns" :key="index">
                <el-descriptions-item
                  label-class-name="font-size-16px"
                  class-name="font-size-16px"
                  :label="item.label"
                  >{{ filedOptions.data[item.key] || '0' }}</el-descriptions-item
                >
              </div>
            </el-descriptions>
          </el-card>
          <DatabaseInfo
            ref="dbInfoRef"
            v-if="activeTab === 'table'"
            :isList="isList"
            :canAdd="route?.query?.canAdd || false"
            class="mt-10px"
            tableShow="table"
            @table-search="countSearch"
          />
        </el-tab-pane>
      </el-tabs>
    </div>
    <Dialog v-model="editFormVisible" title="编辑" width="500px">
      <el-form :model="editForm" :rules="rules" ref="formRef">
        <el-form-item label="归属机构" prop="deptId">
          <el-cascader
            v-model="editForm.deptId"
            clearable
            placeholder="请选择归属机构"
            :options="options"
            :props="cascaderProps"
            filterable
            value-on-clear=""
          />
        </el-form-item>
        <el-form-item label="归属系统" prop="sysId">
          <el-cascader
            v-model="editForm.sysId"
            placeholder="请选择归属系统"
            :props="systemCascaderProps"
            :options="systemList"
            value-on-clear=""
            filterable
            clearable
        /></el-form-item>
        <el-form-item style="margin-bottom: 10px">
          <Icon icon="svg-icon:tips" />
          <span style="color: #cccccc">归属机构与归属系统至少填写一项</span>
        </el-form-item>
        <el-form-item label="数据保护标准" prop="template">
          <el-select v-model="editForm.template" clearable placeholder="请选择数据标准">
            <el-option
              v-for="(template, templateIndex) in templateList"
              :key="templateIndex"
              :label="template.dataStandardName"
              :value="template.id"
            /> </el-select
        ></el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editFormVisible = false" :loading="confirmLoading">取 消</el-button>
          <el-button type="primary" @click="editConfirm" :loading="confirmLoading">
            确 认
          </el-button>
        </div>
      </template>
    </Dialog>
  </ContentWrap>
</template>

<script setup lang="tsx">
import { useRoute } from 'vue-router'
import { DescriptionsProps } from '@/types/descriptions'
import { getDbTreeList } from '@/api/assetDetail'
import { getDataSourceDetail, assetPageByLevelCount, dataSourceUpdate2 } from '@/api/assetList'
import { sourceMap } from '@/utils/dict'
import DatabaseInfo from './components/databaseInfo.vue'
import { getSimpleDeptList } from '@/api/system/dept'
import { getSimpleSystemList } from '@/api/asset/taskManage'
import { handleTree } from '@/utils/tree'
import { List, Menu, Search, Hide, View } from '@element-plus/icons-vue'
import { dataStandardsPage } from '@/api/dataStandards/standards/index'
const route = useRoute()
const assetId = ref<string>(route.query.id as string)
const backOption = ref({
  title: '返回'
})
const dbInfoRef = ref()
const message = useMessage() // 消息弹窗
const isList = ref(true)
const activeTab = ref('field')
const treeData = ref()
const formRef = ref()
const confirmLoading = ref(false)
const editFormVisible = ref(false)
const editForm = ref({
  deptId: '',
  sysId: '',
  template: ''
})
const isShowIp = ref(false)
const cascaderProps = ref({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false
})
const systemCascaderProps = {
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
}
const isRequired = computed(() => {
  return !editForm.value.deptId && !editForm.value.sysId
})
const rules = computed(() => ({
  deptId: [{ required: isRequired.value, message: '归属机构不能为空', trigger: 'change' }],
  sysId: [{ required: isRequired.value, message: '归属系统不能为空', trigger: 'change' }],
  template: [{ required: true, message: '数据保护标准不能为空', trigger: 'change' }]
}))
const infoOptions: DescriptionsProps = reactive({
  column: 5,
  labelSuffix: '：',
  labelWidth: '150px',
  columns: [
    { label: '资产IP:端口', key: 'ip', isShow: true },
    { label: '资产类型', key: 'assetTypeName', isShow: false },
    { label: '库名', key: 'dbName', isShow: false },
    { label: '数据来源', key: 'source', isShow: false },
    { label: '归属系统', key: 'sysName', isShow: true },
    { label: '归属机构', key: 'deptName', isShow: false },
    { label: '数据标准', key: 'templateName', isShow: true },
    // { label: '分类分级方式', key: 'classificationWay', isShow: true },
    { label: '启动时间', key: 'startTime', isShow: true },
    { label: '完成时间', key: 'completeTime', isShow: true }
  ],
  data: {}
})

const filedOptions: DescriptionsProps = reactive({
  column: 5,
  columns: [
    { label: '总数：', key: 'totalCount' },
    { label: '已分级数：', key: 'level' },
    { label: '未分级数：', key: 'unLevel' }
  ],
  data: {}
})

const getTreeList = async () => {
  const res = await getDbTreeList({ id: assetId.value })
  treeData.value = [res.data]
}

const renew = () => {
  getTreeList()
}
const countSearch = async (e) => {
  console.log('e', e)
  const data = await assetPageByLevelCount({
    dataSourceId: assetId.value,
    dataType: activeTab.value === 'field' ? 'column' : 'table',
    ...e
  })
  filedOptions.data = data
}

const getDetail = async () => {
  const res = await getDataSourceDetail({ id: assetId.value })
  infoOptions.data = res.data
  infoOptions.data.deptId = infoOptions.data.deptId == 0 ? '' : infoOptions.data.deptId
  console.log('infoOptions.data', infoOptions.data)
  dbInfoRef?.value?.search()
  dbInfoRef?.value.getDetail()
}

function openEditFormVisible() {
  editForm.value = {
    deptId: infoOptions.data.deptId,
    sysId: infoOptions.data.sysId,
    template: infoOptions.data.template
  }
  editFormVisible.value = true
}
function editConfirm() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        confirmLoading.value = true
        const data = await dataSourceUpdate2({
          ...editForm.value,
          id: assetId.value,
          deptId: editForm.value.deptId == '' ? '0' : editForm.value.deptId
        })
        if (data) {
          message.success('操作成功')
          editFormVisible.value = false
          getDetail()
        }
      } catch {
      } finally {
        confirmLoading.value = false
      }
    }
  })
}

const systemList = ref()
const options = ref()
const getSystemList = async () => {
  const data = await getSimpleSystemList({})
  systemList.value = handleTree(data, 'id', 'pid')
}
const getDeptList = async () => {
  const data = await getSimpleDeptList()
  options.value = data
}

// 数据标准
const templateList = ref([])
const getTemplateList = async () => {
  const { data } = await dataStandardsPage({ page: 1, pageSize: 999, type: 1, status: '1' })
  console.log('data', data)
  templateList.value = data
}

onMounted(async () => {
  getTreeList()
  getDetail()
  getSystemList()
  getDeptList()
  getTemplateList()
})
</script>
